const formInstance = []
window.$CF = {
  formId: '',
  instance: null
}

export default {
  _setformInstance(formId, instance) {
    formInstance.push({
      formId,
      instance
    })
    this._setCF()
  },
  _unsetformInstance(formId) {
    const index = formInstance.findIndex(i => i.formId === formId)
    index !== -1 && formInstance.splice(index, 1)
    this._setCF()
  },
  _setCF() {
    const lastForm = formInstance[formInstance.length - 1]
    if (lastForm) {
      window.$CF = {
        formId: lastForm.formId,
        instance: lastForm.instance
      }
    } else {
      window.$CF = {
        formId: '',
        instance: null
      }
    }
    window._WFchange && window._WFchange()
  },
  _getformInstance(formId) {
    return formInstance.find(i => i.formId === formId)?.instance
  },
  // 刷新
  refresh(formId) {
    const instance = this._getformInstance(formId)
    instance && instance.refreshForm()
  },
  // 刷新
  create(formId) {
    const instance = this._getformInstance(formId)
    instance && instance.createForm()
  },
  // 获取表单
  getFormInstance() {
    const {
      instance
    } = window.$CF
    return instance || null
  },
  // 获取表单
  getFormData() {
    const {
      instance
    } = window.$CF
    if (instance) {
      return instance.getFullFormData()
    }
    return null
  },
  // 暂存表单
  saveForm(validate = false) {
    const {
      instance
    } = window.$CF
    return instance.saveForm(validate)
  },
  // 提交表单
  submitForm(options = {}) {
    const {
      instance
    } = window.$CF
    return instance.submitForm(options)
  },
  // 设置表单数据
  setFormData(fieldName, value) {
    const {
      instance
    } = window.$CF
    if (instance) {
      return instance.setFormData(fieldName, value)
    }
    return null
  },
  // 返回上一级
  redirectToParent() {
    const {
      instance
    } = window.$CF
    instance.redirectToParent()
  }
}
